import Taro, { Component } from '@tarojs/taro'
import { AtTabs, AtTabsPane, AtActionSheet, AtInput, AtModal, AtModalContent, AtModalAction } from 'taro-ui'
import { View, Text, Button, ScrollView } from '@tarojs/components'
import { DNavBar, DCarInfo, DLogistics, DModal, DItemError } from '@/components'
import './myquotes.scss'
import http from '@/api'
import common from '@/common'
export default class myquotes extends Component {

  constructor(props) {
    super(props)
    this.state = {
      active: 0,
      isOpened: false,
      value: '',
      oldVal: '',
      words: '',
      isShow: false,
      isModal: false,
      obj1: {
        page: 1,
        limit: 10
      },
      id: '',
      qptype: '',
      scrollStyle: window.screen.availHeight,
      footerStatus: false,
      totalPage: 1,
      item: [],
      list: []
    }
  }

  componentWillMount() {
    this.getCarQuoteList()
  }
  //我的车辆报价
  getCarQuoteList() {
    let { obj1, totalPage, item, footerStatus } = this.state
    let obj = {
      ...obj1
    }

    if (obj1.page > totalPage) {
      this.setState({
        footerStatus: true
      })
      return
    }
    http.getCarQuoteList(obj).then(res => {
      this.setState({
        item: [...item, ...res.list],
        totalPage: res.totalPage || 1
      })
    })
  }
  //我的物流报价
  myQuoted() {
    let { obj1, totalPage, item } = this.state
    let obj = {
      ...obj1
    }
    if (obj1.page > totalPage) {
      this.setState({
        footerStatus: true
      })
      return
    }
    http.myQuoted(obj).then(res => {
      this.setState({
        item: [...item, ...res.list],
        totalPage: res.totalPage || 1
      })
    })
  }
  //我的报价（已失效）
  myOverdueQuoted() {
    let { obj1, totalPage, item } = this.state
    let obj = {
      ...obj1
    }
    if (obj1.page > totalPage) {
      this.setState({
        footerStatus: true
      })
      return
    }
    http.myOverdueQuoted(obj).then(res => {
      this.setState({
        item: [...item, ...res.list],
        totalPage: res.totalPage || 1
      })
    })
  }
  firstClickMoney(item) {
    this.setState({
      isOpened: true,
      id: item.id,
      value: item.qpPrice
    })
  }
  //修改车辆报价
  changeMycarquote(id) {
    let { value, words } = this.state
    let obj = {
      id: id,
      qpPrice: Number(value).toFixed(2),
      qpRemark: words,
    }
    http.changeMycarquote(obj).then(res => {
      this.setState({
        item: []
      }, () => {
        this.handleClick(0)
      })
    })
  }
  //修改物流报价
  changeQuoted(id) {
    let { value, words } = this.state
    let obj = {
      id: id,
      price: Number(value).toFixed(2),
      remark: words,
    }
    http.changeQuoted(obj).then(res => {
      this.setState({
        item: []
      }, () => {
        this.handleClick(1)
      })
    })
  }
  secodeClickMoney(item) {
    this.setState({
      isShow: true,
      id: item.id
    })
  }
  onCancelModal() {
    this.setState({
      isShow: false,
      isModal: false,
      isOpened: false
    })
  }
  onSubmitHandle = () => {
    let { value, id, active } = this.state

    this.setState({
      isOpened: false
    })

    if (!value) {
      return Taro.showToast({
        icon: 'none',
        title: '请输入修改后报价价格！'
      })
    }

    let indList = this.state.item.filter(list => id == list.id)
    let lPri = 0
    let nVal = this.state.oldVal

    if (indList) {
      if (indList.length) {
        lPri = indList[0].carGuiPrice
      }
    }

    // 改价须在指导价的0.5-2倍之间
    if (value <= lPri * 2 && value >= lPri * 0.5) {
      nVal = value
    } else {
      if (active === 0) {
        Taro.showToast({
          title: "改价须在市场指导价的0.5-2倍之间",
          icon: 'none'
        })
        this.setState({
          value: nVal
        })
        return;
      }
    }

    if (active === 0) {
      this.changeMycarquote(id)
    }
    if (active === 1) {
      this.changeQuoted(id)
    }
  }

  handleChange1(value) {

    this.setState({
      oldVal: this.state.value,
      value: common.getDigit(value, this.state.value),
    })
  }
  handleChange2(words) {
    this.setState({
      words
    })
  }
  handleClick(value) {
    this.setState({
      active: value,
      obj1: {
        page: 1,
        limit: 10
      },
      item: [],
      scrollStyle: window.screen.availHeight,
      footerStatus: false,
      totalPage: 1
    }, () => {
      if (value === 0) {
        this.getCarQuoteList()
      } else if (value === 1) {
        this.myQuoted()
      } else if (value === 2) {
        this.myOverdueQuoted()
      }
    })
  }
  onCancelQuote() {
    let { id, active } = this.state

    this.onCancelModal()
    if (active === 0) {
      this.takeOffMycarQuote(id)
    }
    if (active === 1) {
      this.cancelQuoted(id)
    }
  }
  takeOffMycarQuote(id) {
    http.takeOffMycarQuote({ id: id }).then(res => {
      Taro.showToast({
        title: '取消成功',
        duration: 800,
        mask: true
      }).then(() => {
        setTimeout(() => {
          this.setState({
            item: []
          }, () => {
            this.handleClick(0)
          })
        }, 1000)
      })

    })
  }
  cancelQuoted(id) {
    http.cancelQuoted({ id: id }).then(res => {
      Taro.showToast({
        title: '取消成功',
        duration: 800,
        mask: true
      }).then(() => {
        setTimeout(() => {
          this.handleClick(1)
        }, 1000)
      })

    })
  }
  handleDelete(item) {
    this.setState({
      isModal: true,
      id: item.id,
      qptype: item.qpType
    })
  }
  onDelateQuote() {
    let { id, qptype } = this.state
    this.onCancelModal()
    if (qptype === '1') {
      this.delMycarQuote(id)
    }
    if (qptype === '2') {
      this.deleteQuoted(id)
    }
  }
  delMycarQuote(id) {
    http.delMycarQuote({ id: id }).then(res => {
      Taro.showToast({
        title: '删除成功',
        duration: 800,
        mask: true
      }).then(res => {
        setTimeout(() => {
          this.setState({
            item: []
          }, () => {
            this.handleClick(2)
          })
        }, 1000)
      })

    })
  }
  deleteQuoted(id) {
    http.deleteQuoted({ id: id }).then(res => {
      Taro.showToast({
        title: '删除成功',
        duration: 800,
        mask: true
      }).then(() => {
        setTimeout(() => {
          this.setState({
            item: []
          }, () => {
            this.handleClick(2)
          })
        }, 1000)
      })

    })
  }

  onScroll1 = () => {
    let { obj1, active } = this.state
    if (active !== 0) {
      return
    }
    this.setState({
      obj1: {
        ...this.state.obj1,
        page: obj1.page + 1
      }
    }, () => {
      this.getCarQuoteList()
    })
  }
  onScroll2 = () => {
    let { obj1, active } = this.state
    if (active !== 1) {
      return
    }
    this.setState({
      obj1: {
        ...this.state.obj1,
        page: obj1.page + 1
      }
    }, () => this.myQuoted())
  }
  onScroll3 = () => {
    let { obj1, active } = this.state
    if (active !== 2) {
      return
    }
    this.setState({
      obj1: {
        ...this.state.obj1,
        page: obj1.page + 1
      }
    }, () => this.myOverdueQuoted())
  }
  handleToDetail(id, status) {
    Taro.navigateTo({
      url: `/pages/detail/detail?id=${id}&status=${status}&active=2`
    })
  }
  handleDetail(id) {
    Taro.navigateTo({
      url: `/pages/logisticsinfodetail/logisticsinfodetail?id=${id}&type=logisticsinfodetail`
    })
  }
  handleOverTime() {
    return Taro.showToast({
      title: '该报价已失效',
      icon: 'none'
    })
  }
  render() {
    const tabList = [{ title: '车辆报价' }, { title: '物流报价' }, { title: '已失效' }]
    const {
      active,
      isOpened,
      value,
      words,
      isShow,
      item,
      isModal,
      scrollStyle,
      footerStatus
    } = this.state

    return (
      <View className='b_myquotes'>
        <DNavBar title={'我的报价'} className='b_myquotes_nav'></DNavBar>
        <View className='b_myquotes__box'>
          <View className='b_myquotes__content'>
            <AtTabs current={active} tabList={tabList} onClick={this.handleClick.bind(this)}>
              <AtTabsPane>
                <ScrollView
                  scrollY
                  scrollWithAnimation
                  lowerThreshold='20'
                  style={`height:${scrollStyle - 140}px`}
                  onScrollToLower={this.onScroll1}>
                  {item && item.map((item, i) => {
                    return <DCarInfo
                      key={i}
                      carmoney={item.qpPrice}
                      nameList={[item.carDataModel]}
                      infoList={[item.carSourceType, item.carEmissionStd, '外观颜色:', item.carOutColor,]}
                      place={'卖' + item.carTransDis}
                      money={item.carGuiPrice}
                      company={item.entName + '(' + item.entDis + ')'}
                      clock=''
                      onDetail={this.handleToDetail.bind(this, item.carId, 1)}
                      firstText='重新报价'
                      secodeText='取消报价'
                      firstClick={this.firstClickMoney.bind(this, item)}
                      secodeClick={this.secodeClickMoney.bind(this, item)}
                    >
                    </DCarInfo>
                  })
                  }
                  {
                    footerStatus && <View className='b_myquotes__more'>暂无更多</View>
                  }
                </ScrollView>
              </AtTabsPane>
              <AtTabsPane>
                <ScrollView
                  scrollY
                  scrollWithAnimation
                  lowerThreshold='20'
                  style={`height:${scrollStyle - 140}px`}
                  onScrollToLower={this.onScroll2}>
                  {item && item.map((item, i) => {
                    return <DLogistics
                      startplace={item.cdStart}
                      endplace={item.cdEnd}
                      time={item.cdStartTime}
                      money={item.cdPreMoney}
                      summoney={item.qpPrice}
                      total={item.carCount}
                      firstText='重新报价'
                      secodeText='取消报价'
                      handleDetail={this.handleDetail.bind(this, item.cdId)}
                      onHanldeFirst={this.firstClickMoney.bind(this, item)}
                      onHanldeSecode={this.secodeClickMoney.bind(this, item)}
                    ></DLogistics>
                  })
                  }
                  {
                    footerStatus && <View className='b_myquotes__more'>暂无更多</View>
                  }
                </ScrollView>
              </AtTabsPane>
              <AtTabsPane>
                <ScrollView
                  scrollY
                  scrollWithAnimation
                  lowerThreshold='20'
                  style={`height:${scrollStyle - 140}px`}
                  onScrollToLower={this.onScroll3}>
                  {item && item.map((item, i) => {
                    return <View>
                      {item.qpType === '1' &&
                        <DCarInfo
                          key={i}
                          carmoney={item.qpPrice}
                          nameList={[item.carDataModel]}
                          infoList={[item.carSourceType, item.carEmissionStd, item.carSourcePt, '外观颜色:', item.carOutColor,]}
                          place={item.carTransDis}
                          money={item.carGuiPrice}
                          company={item.entName + '(' + item.entDis + ')'}
                          clock={item.ago}
                          // onDetail={this.handleToDetail.bind(this, item.carId, 2)}
                          firstText='删除'
                          firstClick={this.handleDelete.bind(this, item)}
                        ></DCarInfo>
                      }
                      {item.qpType === '2' &&
                        <DLogistics
                          startplace={item.cdStart}
                          endplace={item.cdEnd}
                          time={item.cdStartTime}
                          money={item.cdPreMoney}
                          summoney={item.qpPrice}
                          total={item.carCount}
                          firstText='删除'
                          handleDetail={this.handleOverTime.bind(this)}
                          onHanldeFirst={this.handleDelete.bind(this, item)}
                        ></DLogistics>
                      }
                    </View>
                  })
                  }
                  {
                    footerStatus && <View className='b_myquotes__more'>暂无更多</View>
                  }
                </ScrollView>
              </AtTabsPane>
            </AtTabs>
            {
              item.length === 0 && <DItemError></DItemError>
            }
          </View>
          <AtActionSheet isOpened={isOpened} onClose={this.onCancelModal.bind(this)}>
            <View className='b_myquotes__money'>
              <Text className='b_myquotes__money_cancel' onClick={this.onCancelModal.bind(this)}>取消</Text>
              <Text className='b_myquotes__money_title'>重新改价</Text>
              <Text className='b_myquotes__money_submit' onClick={this.onSubmitHandle.bind(this)}>提交</Text>
            </View>
            <View className='b_myquotes__input'>
              <AtInput value={value} onChange={this.handleChange1.bind(this)} className='b_myquotes__input_money' title='报价价格' type='number' placeholder='请输入修改后报价'></AtInput>
              <View className='b_myquotes__input_item'>{active === 0 ? '万元' : '元'}</View>
            </View>
            <View className='b_myquotes__input'>
              <AtInput value={words} onChange={this.handleChange2.bind(this)} className='b_myquotes__input_money' title='留言' type='text' placeholder='可给经销商留言'></AtInput>
            </View>
          </AtActionSheet>
          <AtModal isOpened={isShow} className='b_myquotes__modal' onClose={this.onCancelModal.bind(this)}>
            <AtModalContent>
              <Text className='b_myquotes__modal_title'>提示</Text>
              确认撤回此次报价吗？
          </AtModalContent>
            <AtModalAction>
              <Button onClick={this.onCancelModal.bind(this)}>取消</Button>
              <Button className='b_myquotes__modal_confirm' onClick={this.onCancelQuote.bind(this)}>确定</Button>
            </AtModalAction>
          </AtModal>
        </View>
        <DModal
          isShow={isModal}
          title='提示'
          text='确定要删除订单吗？'
          firstbtn='取消'
          lastbtn='确认'
          onFirst={this.onCancelModal.bind(this)}
          onCancel={this.onCancelModal.bind(this)}
          onLast={this.onDelateQuote.bind(this)}
        ></DModal>
      </View>

    )
  }
}
